"""
pyinsight - library for low-level, black magic inspections within python code
"""
import sys
import struct
import dis

_VERSION = (0, 0, 1)

def get_retval_recipient(level=1):
    """
    gets the name of the variable to which the return
    value of the calling function is to be returned.

    >>> def testfunc():
    ...     i = 2
    ...     j = 3
    ...     bla = otherfunc()
    ...     k = 666
    >>> def otherfunc():
    ...     print get_retval_recipient()
    >>> testfunc()
    bla
    """
    frame = sys._getframe(level + 1)
    try:
        code = frame.f_code.co_code
        next_instruction = frame.f_lasti + 3
        opcode = ord(code[next_instruction])
        if dis.opname[opcode] != 'STORE_FAST':
            return None
        operand = struct.unpack("h",
                                code[next_instruction + 1: next_instruction + 3])[0]
        name = frame.f_code.co_varnames[operand]
        
        return name
    finally:
        #frames might cause cyclic references...
        del frame  
   
if __name__ == "__main__":
    import doctest
    doctest.testmod()
